/**
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.profile;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.active.DictionaryAdapter;
import com.tstudy.laoshibang.active.DictionaryAdapter.ActionCallBack;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.event.SelectAddressEvent;
import com.tstudy.laoshibang.login.NeedLoginFragment;
import com.tstudy.laoshibang.manager.CityManager;
import com.tstudy.laoshibang.mode.City;
import com.tstudy.laoshibang.mode.Dictionary;
import com.tstudy.laoshibang.mode.response.QueryAddressResponse;
import com.tstudy.laoshibang.utils.LogUtil;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import de.greenrobot.event.EventBus;
@EFragment(R.layout.select_school)
public class SelectSchoolFragment extends NeedLoginFragment{
	final static String TAG = "select_school";
	public SelectSchoolFragment() {
		super();
	}
	
	@ViewById(R.id.select_school_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.select_school_county_list)
	ListView  countyListView;
	
	@ViewById(R.id.select_school_list)
	ListView  schoolListView;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	List<Dictionary> countyList;
	List<Dictionary> schoolList;
	DictionaryAdapter countyAdapter;
	DictionaryAdapter schoolAdapter;
	Dictionary mSelectCity;
	Dictionary mSelectCounty;
	Dictionary mSelectSchool;
	Dictionary mSelectLevel;

	public static void add(int containerViewId,Dictionary selectCity,Dictionary selectCounty,Dictionary selectSchool,Dictionary selectLevel) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,SelectSchoolFragment_.class.getName(),args);
		((SelectSchoolFragment)fragment).mSelectCity = selectCity;
		((SelectSchoolFragment)fragment).mSelectCounty = selectCounty;
		((SelectSchoolFragment)fragment).mSelectSchool = selectSchool;
		((SelectSchoolFragment)fragment).mSelectLevel = selectLevel;
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			countyAdapter = new DictionaryAdapter();
			schoolAdapter = new DictionaryAdapter();
			countyListView.setAdapter(countyAdapter);
			schoolListView.setAdapter(schoolAdapter);
			countyList = buildCountyList(mSelectCity);
			countyAdapter.setData(countyList);
			if (mSelectCounty != null) {
				querySchool(mSelectCounty.code);
			}else{
				querySchool(countyList.get(0).code);
			}
			countyAdapter.setData(countyList);
			schoolAdapter.setData(schoolList);
			countyAdapter.setActionCallBack(new ActionCallBack() {
				@Override
				public void onItemClick(Dictionary dictionary,int position) {
					if (mSelectCounty != null) {
						mSelectCounty.isSelected =  false;
					}
					mSelectCounty = dictionary;
					mSelectCounty.isSelected = true;
					countyAdapter.setData(countyList);
					querySchool(mSelectCounty.code);
				}
			});
			schoolAdapter.setActionCallBack(new ActionCallBack() {
				@Override
				public void onItemClick(Dictionary dictionary,int position) {
					if (mSelectSchool != null) {
						mSelectSchool.isSelected =  false;
					}
					mSelectSchool = dictionary;
					mSelectSchool.isSelected = true;
					SelectAddressEvent addressEvent = new SelectAddressEvent();
					addressEvent.selectType = Dictionary.TYPE_SCHOOL;
					addressEvent.firstCol = mSelectCounty;
					addressEvent.secondCol = dictionary;
					schoolAdapter.setData(schoolList);
					EventBus.getDefault().post(addressEvent);
					backAction(mFragmentId);
				}
			});
			
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Dictionary> buildCountyList(Dictionary dictionary){
		List<City> cityList = null;
		cityList = CityManager.getInstance().queryByField("parentCityId",dictionary.code);
		List<Dictionary> dicList = new ArrayList<Dictionary>();
		if (cityList != null) {
			int size = cityList.size();
			for (int i = 0; i < size; i++) {
				Dictionary each = new Dictionary();
				City city = cityList.get(i);
				each.type = Dictionary.TYPE_COUNTY;
				each.code = city.getCityId();
				each.name = city.getCityName();
				if (mSelectCounty != null && each.code==mSelectCounty.code) {
					each.isSelected = true;
					mSelectCounty = each;
				}else if (i == 0) {
					each.isSelected = true;
					mSelectCounty = each;
				}
				dicList.add(each);
			}
		}
		return dicList;
	}
	
	/**
	 * 获取学校信息
	 */
	public void querySchool(int areaCode){
		ResponseHandlerInterface response = new BaseJsonHandler<QueryAddressResponse>() {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, QueryAddressResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (response != null && response.getErr() == CONSTANT.NO_ERROR_STATUS) {
					schoolList = response.getData().getList();
					if (schoolList != null) {
						int size = schoolList.size();
						for (int i = 0; i < size; i++) {
							Dictionary each = schoolList.get(i);
							if (mSelectSchool != null && mSelectSchool.code == each.code) {
								schoolList.get(i).isSelected = true;
							}
						}
					}
					schoolAdapter.setData(schoolList);
				} else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			protected QueryAddressResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,QueryAddressResponse.class);
			}
		};
		int type = 0;
		if (mSelectLevel != null) {
			type = mSelectLevel.code;
		}
		HttpManager.getInstance().querySchool(BaseApplication.mUserNo,areaCode, type, response);
	}
	
	@Click({R.id.select_school_back,R.id.select_school_commit})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.select_school_back:
			backAction(mFragmentId);
			break;
		case R.id.select_school_commit:
			break;
		default:
			break;
		}
	}
	
	@Override
	public void clear() {
		
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
